package com.xxx.client.loadbalance;

import com.xxx.client.handler.RemoteCallClient;
import com.xxx.client.registry.ChannelInfo;
import com.xxx.registry.ZkUtils;
import org.apache.curator.framework.CuratorFramework;

import java.util.Collection;
import java.util.Comparator;
import java.util.Optional;

/**
 * Created by louisyuu on 2020/4/30 下午3:25
 */
public class LastResponseTimeLoadbalancer implements Loadbalancer {


    @Override
    public ChannelInfo getClient() {


        Collection<ChannelInfo> values = RemoteCallClient.getInstance().getAvailableServers().values();
        if (values.isEmpty()) {
            return null;
        }
        CuratorFramework zkClient = ZkUtils.getZkClient();
        Optional<ChannelInfo> optional = values.stream()
                .min(Comparator.comparingLong(e -> {
                    byte[] bytes = new byte[0];
                    try {
                        bytes = zkClient.getData().forPath(e.getServerInfo().getServerPath());
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }

                    String lasts = new String(bytes);

                    if (lasts.length() > 0) {
//                        System.out.println("======The server last response time lasts " + lasts);
                        return Long.valueOf(lasts);
                    } else {
//                        System.out.println("======The server have no last response time record");
                        return -1L;

                    }
                }));
        ChannelInfo channelInfo = optional.get();
        if (channelInfo != null) {
            System.out.println("=====" + channelInfo.getServerInfo().getServerAddress() + " has been selected");
        }
        return channelInfo;


    }
}
